package RPC;

import com.rabbitmq.client.*;
import constant.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * 发送消息
 * 接收消息
 */
public class RPCClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USERNAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        //创建信道
        Channel channel = connection.createChannel();

        /**
         * 声明队列
         */
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE, true, false, false, null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE, true, false, false, null);

        //发送消息
        String message = "hello rpc";
        //配置参数
        String correlationId = UUID.randomUUID().toString();
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .correlationId(correlationId)
                .replyTo(Constants.RPC_RESPONSE_QUEUE) //服务器通过哪个队列给客户端发送消息
                .build();
        channel.basicPublish("", Constants.RPC_REQUEST_QUEUE, props, message.getBytes(StandardCharsets.UTF_8));

        //接收消息
        //使用阻塞队列
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(1);
        //消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String resultMessage = new String(body);
                System.out.println("接收到的消息: " + resultMessage);

                //判断客户端的 correlation 与 服务器发送过来的 correlation 是否相同
                //相同，就表示这条消息是响应
                if (correlationId.equals(properties.getCorrelationId())) {
                    queue.offer(resultMessage);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE, true, consumer);
        String response = queue.take();
        System.out.println("客户端接收结果: " + response);

    }
}
